import { defineStore } from 'pinia';
import db from '../database';
import { toRaw } from 'vue';

export interface SceneData {
    id: string;
    event: string | null;// 使用的事件表id
    data: any;
}

interface ScenesState {
    scenes: SceneData[];
}

const Key = 'scenes';
export const scenesStore = defineStore('scenes', {
    state: (): ScenesState => {
        return {
            scenes: [],
        };
    },
    actions: {
        init(data: ScenesState) {
            this.scenes = data.scenes;
        },
        toConfig() {
            return {
                key: Key,
            };
        },
        getSceneData(id: string) {
            const ret = this.getScene(id);
            if (ret) {
                return toRaw(ret.data);
            }
            return null;
        },
        getScene(id: string): SceneData | null {
            return this.scenes.find(el => el.id === id) || null;
        },
        addScene(id: string) {
            const item: SceneData = {
                id,
                event: null,
                data: [],
            };
            this.scenes.push(item);
        },
        removeScene(id: string) {
            const idx = this.scenes.findIndex(el => el.id === id);
            if (idx !== -1) {
                this.scenes.splice(idx, 1);
            }
        },
        saveScene(id: string, data: any) {
            const ret = this.scenes.find(el => el.id === id);
            if (ret) {
                ret.data = data;
                db.save();
            }
        },
        changeSceneEvent(id: string, event: string) {
            const ret = this.scenes.find(el => el.id === id);
            if (ret && ret.event !== event) {
                ret.event = event;
                db.save();
            }
        },
    },
});